package com.rosh.rpc.client.proxy;

import com.rosh.rpc.client.request.RpcRequestManager;
import com.rosh.rpc.core.data.RpcRequest;
import com.rosh.rpc.core.data.RpcResponse;
import com.rosh.rpc.core.spring.SpringBeanFactory;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Method;
import java.util.UUID;

/**
 * @Description:
 * @Author: rosh
 * @Date: 2022/6/14 20:17
 */
public class CglibProxyCallBackHandler implements MethodInterceptor {

    /**
     *
     * @param proxy  对象
     * @param method  目标对象的方法
     * @param parameters 目标对象方法的参数
     * @param methodProxy 代理对象中,代理方法对象
     *
     * @return 代理对象
     */
    @Override
    public Object intercept(Object proxy, Method method, Object[] parameters, MethodProxy methodProxy) throws Throwable {

        //放过toString,hashcode，equals等方法，采用spring工具类
        if (ReflectionUtils.isObjectMethod(method)) {
            return method.invoke(method.getDeclaringClass().newInstance(), parameters);
        }

        //获取相关参数
        String requestId = UUID.randomUUID().toString();
        String className = method.getDeclaringClass().getName();
        String methodName = method.getName();
        Class<?>[] parameterTypes = method.getParameterTypes();
        //封装rpcRequest
        RpcRequest request = new RpcRequest(requestId, className, methodName, parameterTypes, parameters);
        //获取请求管理器
        RpcRequestManager rpcRequestManager = SpringBeanFactory.getBean(RpcRequestManager.class);
        //发起请求
        RpcResponse response = rpcRequestManager.sendRequest(request);
        return response.getResult();
    }
}
